import threading
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from apscheduler.schedulers.background import BackgroundScheduler

"""
封装定时任务
使用方法:
MyScheduler().register(method_name, second="*/"+self.__freq, hour="*", minute="*")
"""

Lock = threading.Lock()

class MyScheduler(object):
    
    # 定义静态变量实例
    __scheduler = None
    
     
    __executors = {
        'default': ThreadPoolExecutor(100),
        'processpool': ProcessPoolExecutor(50)
    }
    
    __job_defaults = {
        'coalesce': True,
        'max_instances': 100,#同时运行的任务数量
        'misfire_grace_time': 70
    }
    
    def __init__(self):
        self.__scheduler = BackgroundScheduler(executors=self.__executors, job_defaults=self.__job_defaults)
        self.__scheduler.start()
    
    def __new__(self, *args, **kwargs):
        if not self.__scheduler:
            try:
                Lock.acquire()
                if not self.__scheduler:
                    self.__scheduler = super(MyScheduler,self).__new__(self,*args, **kwargs)
            finally:
                Lock.release()
        return self.__scheduler
    
    
    def register(self,func=None, second=None, hour=None, minute=None):
        return self.__scheduler.add_job(func,'cron', second=second, hour=hour, minute=minute)
    
    
